package com.yedean.factory.support;

import cn.hutool.core.util.StrUtil;
import com.yedean.factory.config.BeanDefinition;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class DisposableBeanAdapter implements DisposableBean{
    
    private Object bean;
    
    private String beanName;
    
    private String destroyMethod;
    
    @Override
    public void destroy() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        if (bean instanceof DisposableBean){
            ((DisposableBean)bean).destroy();
        }
        if (StrUtil.isNotEmpty(destroyMethod)&&!(bean instanceof DisposableBean)&&"destroyDataMethod".equals(destroyMethod)){
            Method destroyMethod = bean.getClass().getMethod(this.destroyMethod);
            destroyMethod.invoke(bean);
        }
    }

    public DisposableBeanAdapter(Object bean, String beanName, BeanDefinition definition) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethod = definition.getDestroyMethodName();
    }
}
